package com.sweetest.luffy.vo;


import lombok.Synchronized;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 公共工具类
 */
public class CommonUtil {

    //2000年的秒数
    private static Long num = 943891200000L;


    public static boolean checkNull(Object... args) {

        boolean flag = false;
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                Object param = args[i];
                //判断是否为Null
                if (param == null) {
                    flag = true;
                    break;
                }
                //字符串等类型还需要做多重判断
                if (param instanceof String && StringUtils.isBlank(param.toString())) {
                    flag = true;
                    break;
                }
                if (param instanceof Integer && 0 == Integer.parseInt(param.toString())) {
                    flag = true;
                    break;
                }
                if (param.getClass().isArray() && Array.getLength(param) == 0) {
                    flag = true;
                    break;
                }
                if (param instanceof Collection && ((Collection) param).isEmpty()) {
                    flag = true;
                    break;
                }
                if (param instanceof Map && ((Map) param).isEmpty()) {
                    flag = true;
                    break;
                }
            }
        } else {
            flag = true;
        }
        return flag;
    }


    public static boolean isPhoneNo(String mobiles) {
        boolean flag;
        try {
            Pattern p = Pattern.compile("^[1][^012][0-9]{9}$");
            Matcher m = p.matcher(mobiles);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    //2000到现在的毫秒数
    @Synchronized
    public static Long getOrderId() {
        Date date = new Date();
        return date.getTime() - num;
    }

//    public String getStroageUrl(String name) {
//        return String.format("%s/%s", S.QINIU_STORAGE_DOMAIN, name);
//    }

    /**
     * MD5加密
     */
    public final static String MD5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] strTemp = s.getBytes();
            // 使用MD5创建MessageDigest对象
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte b = md[i];
                str[k++] = hexDigits[b >> 4 & 0xf];
                str[k++] = hexDigits[b & 0xf];
            }
            return new String(str).toUpperCase();
        } catch (Exception e) {
            return null;
        }
    }

    public static String MD5s(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }


    public static Map<String, String> parseXml(HttpServletRequest request)
            throws Exception {
        // 解析结果存储在HashMap
        Map<String, String> map = new HashMap<String, String>();
        InputStream inputStream = request.getInputStream();
        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        @SuppressWarnings("unchecked")
        List<Element> elementList = root.elements();

        // 遍历所有子节点
        for (Element e : elementList)
            map.put(e.getName(), e.getText());

        // 释放资源
        inputStream.close();
        inputStream = null;

        return map;
    }

    public static String stringToXml(Map<String, Object> parameters) {
        if (parameters != null) {
            StringBuffer xml = new StringBuffer();
            xml.append("<xml>");

            xml.append("<appid><![CDATA[");
            xml.append(parameters.get("appid"));
            xml.append("]]></appid>");

            xml.append("<body><![CDATA[");
            xml.append(parameters.get("body"));
            xml.append("]]></body>");

            xml.append("<fee_type><![CDATA[");
            xml.append(parameters.get("fee_type"));
            xml.append("]]></fee_type>");

            xml.append("<mch_id><![CDATA[");
            xml.append(parameters.get("mch_id"));
            xml.append("]]></mch_id>");

            xml.append("<nonce_str><![CDATA[");
            xml.append(parameters.get("nonce_str"));
            xml.append("]]></nonce_str>");

            xml.append("<notify_url><![CDATA[");
            xml.append(parameters.get("notify_url"));
            xml.append("]]></notify_url>");

            xml.append("<out_trade_no><![CDATA[");
            xml.append(parameters.get("out_trade_no"));
            xml.append("]]></out_trade_no>");

            xml.append("<spbill_create_ip><![CDATA[");
            xml.append(parameters.get("spbill_create_ip"));
            xml.append("]]></spbill_create_ip>");

            xml.append("<time_expire><![CDATA[");
            xml.append(parameters.get("time_expire"));
            xml.append("]]></time_expire>");

            xml.append("<time_start><![CDATA[");
            xml.append(parameters.get("time_start"));
            xml.append("]]></time_start>");

            xml.append("<total_fee><![CDATA[");
            xml.append(parameters.get("total_fee"));
            xml.append("]]></total_fee>");

            xml.append("<trade_type><![CDATA[");
            xml.append(parameters.get("trade_type"));
            xml.append("]]></trade_type>");

            xml.append("<sign><![CDATA[");
            xml.append(parameters.get("sign"));
            xml.append("]]></sign>");

            xml.append("</xml>");
            return xml.toString();
        } else {
            return "";
        }
    }

    /**
     * 随机字符串
     *
     * @return
     */
    public static String randomString(int size) {
        StringBuffer array = new StringBuffer();
        for (int i = 0; i <= 9; i++) {
            array.append(i);
        }
        // 小写字母暂时不要
        // for (int i = (int) 'a'; i <= (int) 'z'; i++) {
        // array.append((char) i);
        // }
        for (int i = (int) 'A'; i <= (int) 'Z'; i++) {
            array.append((char) i);
        }
        int length = array.length();

        // 假设n现在为100
        int n = size;
        // 存储最后生成的字符串
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < n; i++) {
            // 获得随机位置的字符
            char c = array.charAt((int) (Math.random() * length));
            str.append(c);
        }
        return str.toString();
    }


}
